package gepetto.message;

import java.util.TreeMap;

public class AttrSet {
	private String id;
	private TreeMap<String, String> attrs;
	private TreeMap<String, AttrSet> sets;
	
	public AttrSet (String id) {
		this.id = id;
		this.attrs = new TreeMap<String, String> ();
		this.sets  = new TreeMap<String, AttrSet> ();
	}

	public String getId() {
		return id;
	}

	public void setId(String id) {
		this.id = id;
	}
	
	public void put (String key, String value) {
		System.out.println("Putting (" + key + ","+ value +") into " + this.id);
		Tuple tuple = new Tuple (this, key);
		if (tuple.isAttr()) {
			attrs.put(tuple.subkey, value);
		}
		else {
			AttrSet set;
			if (tuple.existSet()) {
				set = tuple.set;
			}
			else {				
				set = new AttrSet (tuple.subset);
				sets.put (set.id, set);
			}
			set.put (tuple.subkey, value);
		}
	}
	
	public String get (String key) {
		Tuple tuple = new Tuple (this, key);
		if (tuple.isAttr()) {
			return attrs.get(tuple.subkey);
		}
		else {
			if (tuple.existSet()) {
				tuple.set.get(tuple.subkey);
			}
		}
		return null;
	}
	
	TreeMap<String,String> getAttrs () {
		return attrs;
	}
	
	TreeMap<String,AttrSet> getAttrSets () {
		return sets;
	}
	
	private class Tuple {
		public AttrSet set;
		public String subset;
		public String subkey;
		
		public Tuple (AttrSet aset, String key) {
			int index = key.indexOf('.');
			if (index >= 0) {
				subset = key.substring(0, index);
				if (aset.sets.containsKey (subset)) {
					set = sets.get (subset);
				}
				subkey = key.substring (index + 1);
			}
			else {
				subkey = key;
			}
		}
		
		public boolean isAttr () {
			return subset == null;
		}
		
		public boolean existSet () {
			return set != null;
		}
	}
}
